package com.weilan.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.weilan.blog.admin.mapper.BlogCategoryMapper;
import com.weilan.blog.admin.service.BlogCategoryService;
import com.weilan.blog.admin.service.BlogService;
import com.weilan.blog.admin.vo.BlogCategoryVO;
import com.weilan.blog.base.enums.EPublish;
import com.weilan.blog.base.enums.EStatus;
import com.weilan.blog.base.serviceImpl.SuperServiceImpl;
import com.weilan.blog.admin.entity.Blog;
import com.weilan.blog.admin.entity.BlogCategory;
import com.weilan.blog.utils.ResultUtil;
import com.weilan.blog.utils.StringUtils;
import com.weilan.blog.common.global.MessageConf;
import com.weilan.blog.common.global.SQLConf;
import com.weilan.blog.common.global.SysConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 孙 峰
 * @time: 2020/9/23 14:31
 */
@Service
public class BlogCategoryServiceImpl extends SuperServiceImpl<BlogCategoryMapper, BlogCategory> implements BlogCategoryService {

    @Autowired
    private BlogCategoryService blogCategoryService;

    @Autowired
    private BlogService blogService;

    @Override
    public IPage<BlogCategory> getPageList(BlogCategoryVO blogCategoryVO) {
        QueryWrapper<BlogCategory> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(blogCategoryVO.getKeyword()) && !StringUtils.isEmpty(blogCategoryVO.getKeyword().trim())) {
            queryWrapper.like(SQLConf.CATEGORY_NAME, blogCategoryVO.getKeyword().trim());
        }
        Page<BlogCategory> page = new Page<>();
        page.setCurrent(blogCategoryVO.getCurrentPage());
        page.setSize(blogCategoryVO.getPageSize());
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        IPage<BlogCategory> pageList = blogCategoryService.page(page, queryWrapper);
        return pageList;
    }

    @Override
    public List<BlogCategory> getList() {
        QueryWrapper<BlogCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SysConf.STATUS, EStatus.ENABLE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        List<BlogCategory> BlogCategoryList = blogCategoryService.list(queryWrapper);
        return BlogCategoryList;
    }

    @Override
    @Transactional
    public String addBlogCategory(BlogCategoryVO BlogCategoryVO) {
        // 判断添加的分类是否存在
        QueryWrapper<BlogCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.CATEGORY_NAME, BlogCategoryVO.getCategoryName());
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        // 判断数据库是否存在
        BlogCategory tempSort = blogCategoryService.getOne(queryWrapper);
        if (tempSort != null) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.ENTITY_EXIST);
        }

        BlogCategory BlogCategory = new BlogCategory();
        BlogCategory.setContent(BlogCategoryVO.getContent());
        BlogCategory.setCategoryName(BlogCategoryVO.getCategoryName());
        BlogCategory.setSort(BlogCategoryVO.getSort());
        BlogCategory.setStatus(EStatus.ENABLE);
        BlogCategory.insert();
        return ResultUtil.result(SysConf.SUCCESS, MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String editBlogCategory(BlogCategoryVO BlogCategoryVO) {
        BlogCategory BlogCategory = blogCategoryService.getById(BlogCategoryVO.getUid());
        /**
         * 判断需要编辑的博客分类是否存在
         */
        if (!BlogCategory.getCategoryName().equals(BlogCategoryVO.getCategoryName())) {
            QueryWrapper<BlogCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SQLConf.CATEGORY_NAME, BlogCategoryVO.getCategoryName());
            queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
            BlogCategory tempSort = blogCategoryService.getOne(queryWrapper);
            if (tempSort != null) {
                return ResultUtil.result(SysConf.ERROR, MessageConf.ENTITY_EXIST);
            }
        }
        BlogCategory.setContent(BlogCategoryVO.getContent());
        BlogCategory.setCategoryName(BlogCategoryVO.getCategoryName());
        BlogCategory.setSort(BlogCategoryVO.getSort());
        BlogCategory.setStatus(EStatus.ENABLE);
        BlogCategory.setUpdateTime(LocalDateTime.now());
        BlogCategory.updateById();
        // 删除和博客相关的Redis缓存
        //blogService.deleteRedisByBlogCategory();
        return ResultUtil.result(SysConf.SUCCESS, MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String deleteBatchBlogCategory(List<BlogCategoryVO> blogCategoryVoList) {
        if (blogCategoryVoList.size() <= 0) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
        }
        List<String> uids = new ArrayList<>();

        blogCategoryVoList.forEach(item -> {
            uids.add(item.getUid());
        });

        // 判断要删除的分类，是否有博客
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        blogQueryWrapper.in(SQLConf.BLOG_SORT_UID, uids);
        Integer blogCount = blogService.count(blogQueryWrapper);
        if (blogCount > 0) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.BLOG_UNDER_THIS_SORT);
        }
        Collection<BlogCategory> blogCategoryList = blogCategoryService.listByIds(uids);
        blogCategoryList.forEach(item -> {
            item.setUpdateTime(LocalDateTime.now());
            //  将数据状态设置为不可用
            item.setStatus(EStatus.DISABLED);
        });
        Boolean save = blogCategoryService.updateBatchById(blogCategoryList);
        if (save) {
            // 删除和博客相关的Redis缓存
            blogService.deleteRedisByBlogCategory();
            return ResultUtil.result(SysConf.SUCCESS, MessageConf.DELETE_SUCCESS);
        } else {
            return ResultUtil.result(SysConf.ERROR, MessageConf.DELETE_FAIL);
        }
    }

    /**
     * 根据id批量删除
     * @param ids
     * @return
     */
    @Override
    public String deleteBatchBlogCategory(String[] ids) {
        List<String> idList = Arrays.stream(ids).collect(Collectors.toList());
        if (ids.length <= 0) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
        }
        // 判断要删除的分类，是否有博客
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        blogQueryWrapper.in(SQLConf.BLOG_SORT_UID, idList);

        Integer blogCount = blogService.count(blogQueryWrapper);
        if (blogCount > 0) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.BLOG_UNDER_THIS_SORT);
        }
        Collection<BlogCategory> blogCategoryList = blogCategoryService.listByIds(idList);
        blogCategoryList.forEach(item -> {
            item.setUpdateTime(LocalDateTime.now());
            //  将数据状态设置为不可用
            item.setStatus(EStatus.DISABLED);
        });
        Boolean save = blogCategoryService.updateBatchById(blogCategoryList);
        if (save) {
            // 删除和博客相关的Redis缓存
            blogService.deleteRedisByBlogCategory();
            return ResultUtil.result(SysConf.SUCCESS, MessageConf.DELETE_SUCCESS);
        } else {
            return ResultUtil.result(SysConf.ERROR, MessageConf.DELETE_FAIL);
        }
    }

    @Override
    public String stickBlogCategory(BlogCategoryVO BlogCategoryVO) {
        BlogCategory BlogCategory = blogCategoryService.getById(BlogCategoryVO.getUid());

        //查找出最大的那一个
        QueryWrapper<BlogCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(SQLConf.SORT);
        Page<BlogCategory> page = new Page<>();
        page.setCurrent(0);
        page.setSize(1);
        IPage<BlogCategory> pageList = blogCategoryService.page(page, queryWrapper);
        List<BlogCategory> list = pageList.getRecords();
        BlogCategory maxSort = list.get(0);

        if (StringUtils.isEmpty(maxSort.getUid())) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
        }
        if (maxSort.getUid().equals(BlogCategory.getUid())) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.THIS_SORT_IS_TOP);
        }
        Integer sortCount = maxSort.getSort() + 1;
        BlogCategory.setSort(sortCount);
        BlogCategory.setUpdateTime(LocalDateTime.now());
        BlogCategory.updateById();
        return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS);
    }

    @Override
    public String blogCategoryByClickCount() {
        QueryWrapper<BlogCategory> queryWrapper = new QueryWrapper();

        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);

        // 按点击从高到低排序
        queryWrapper.orderByDesc(SQLConf.CLICK_COUNT);

        List<BlogCategory> BlogCategoryList = blogCategoryService.list(queryWrapper);

        // 设置初始化最大的sort值
        Integer maxSort = BlogCategoryList.size();
        for (BlogCategory item : BlogCategoryList) {
            item.setSort(item.getClickCount());
            item.setUpdateTime(LocalDateTime.now());
        }
        blogCategoryService.updateBatchById(BlogCategoryList);
        return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS);
    }

    @Override
    public String blogCategoryByCite() {
        // 定义Map   key：tagUid,  value: 引用量
        Map<String, Integer> map = new HashMap<>();

        QueryWrapper<BlogCategory> BlogCategoryQueryWrapper = new QueryWrapper<>();
        BlogCategoryQueryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        List<BlogCategory> BlogCategoryList = blogCategoryService.list(BlogCategoryQueryWrapper);
        // 初始化所有标签的引用量
        BlogCategoryList.forEach(item -> {
            map.put(item.getUid(), 0);
        });

        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH);
        // 过滤content字段
        queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT));
        List<Blog> blogList = blogService.list(queryWrapper);

        blogList.forEach(item -> {
            String BlogCategoryUid = item.getBlogCategoryUid();
            if (map.get(BlogCategoryUid) != null) {
                Integer count = map.get(BlogCategoryUid) + 1;
                map.put(BlogCategoryUid, count);
            } else {
                map.put(BlogCategoryUid, 0);
            }
        });

        BlogCategoryList.forEach(item -> {
            item.setSort(map.get(item.getUid()));
            item.setUpdateTime(LocalDateTime.now());
        });
        blogCategoryService.updateBatchById(BlogCategoryList);

        return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS);
    }

    @Override
    public BlogCategory getTopOne() {
        QueryWrapper<BlogCategory> BlogCategoryQueryWrapper = new QueryWrapper<>();
        BlogCategoryQueryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        BlogCategoryQueryWrapper.last(SysConf.LIMIT_ONE);
        BlogCategoryQueryWrapper.orderByDesc(SQLConf.SORT);
        BlogCategory BlogCategory = blogCategoryService.getOne(BlogCategoryQueryWrapper);
        return BlogCategory;
    }
}
